/*
 * ====================================================================
 * Copyright (C) 2013 Eric Blond
 *
 * This file is part of Neptune.
 *
 * Neptune is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Neptune is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Neptune.  If not, see <http://www.gnu.org/licenses/>.
 * ====================================================================
 */

package com.hyperplan.neptune.command;

import java.util.List;
import java.util.Map;

import com.hyperplan.neptune.SourceElement;
import com.hyperplan.neptune.SourceManager;
import com.hyperplan.neptune.lexer.Lexer;
import com.hyperplan.neptune.lexer.LexerException;
import com.hyperplan.neptune.lexer.Token;
import com.hyperplan.neptune.utils.Block;

public class LexCommand extends Command {

	public String getName() {
		return "lex";
	}
	
	private static final String PARAM_DUMP = "dump";
	
	public String[] getParameters() {
		return new String[] { PARAM_DUMP };
	}
	
	public void execute(Map<String, String> mapping) throws Exception {
		boolean dump = false;
		if (mapping.containsKey(PARAM_DUMP)) {
			dump = parseBoolean(mapping.get(PARAM_DUMP));
		}
		SourceManager manager = new SourceManager();
		for (Map.Entry<String, SourceElement> element
				: manager.getMapping().entrySet()) {
			lex(element.getValue(), dump);
		}
	}
		
	private void lex(SourceElement element, boolean dump) throws Exception {
		System.out.print(String.format("Lexing module [%s] (in [%s])...",
				element.getModuleName(), element.getRoot()));
		try {
			List<Token> tokens = Lexer.run(element.getPath());
			System.out.println(" Ok.");
			if (dump) {
				Block children = new Block();
				for (Token token : tokens) {
					children.addVertically(token.getBlock());
				}
				children.addTop('=');
				children.addBottom('=');
				children.dump(System.out);
			}
		}
		catch (LexerException exception) {
			System.out.println(" Failed!");
			System.out.println(String.format(" => %s", exception.getMessage()));
		}
	}
}
